/*
 * @(#)ListLinks.java $version 2012-3-26
 * 
 * Copyright 2011 RogueDevelopment Gruop. All rights Reserved.
 * ROGUEDEVELOPMENT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nadostar.extensions.jsoup;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @author LEESUNG
 * 
 */
public class ListLinksTest {
	public static void main(String[] args) throws IOException {
		String url = "http://www.1qdisk.com/vod/view.html?idx=3666";
		
		TargetMovieInfo movieInfo = new TargetMovieInfo();
		
		movieInfo.setUrl(url);
		print("Fetching %s...", url);

		Document doc = Jsoup.connect(url).get();
		
		print("Title %s...\n", doc.select("table.vod_list_top").select("tr td:eq(0)").text());
		
		Element vod_list = doc.getElementById("video_list");
		Elements childTrElement = vod_list.getElementsByTag("tr");
		
		List<TargetMovieLink> targetLinkList = new ArrayList<TargetMovieLink>();
		for(Element el : childTrElement) {
			
			String subTitle = el.select("td:eq(1)").text();
			String ylink = el.select("td:eq(2)").select("img").attr("onclick");
			String tlink = el.select("td:eq(3)").select("a").attr("onclick");
			if(ylink.length() > 0) {
				if(ylink.indexOf(",") > 0) {
					ylink = URLDecoder.decode(ylink.split(",")[0].replace("player(\'", "").replace("\'", ""), "UTF-8");
				}
			}
			
			if(tlink.length() > 0) {
				if(tlink.indexOf(",") > 0) {
					tlink = URLDecoder.decode(tlink.split(",")[0].replace("playerTwoddo(\'", "").replace("\'", ""), "UTF-8");
				}
			}
			
			if(subTitle.length() > 0) {
				
				print("TITLE: %s", subTitle);
				print("YOUKU: %s", URLDecoder.decode(ylink, "UTF-8"));
				print("TUDOU: %s", URLDecoder.decode(tlink, "UTF-8"));
				print("\n", "");
				
				TargetMovieLink movieLink = new TargetMovieLink();
				movieLink.setTitle(subTitle);
				movieLink.setLink(URLDecoder.decode(ylink, "UTF-8"));
				movieLink.setLink2(URLDecoder.decode(tlink, "UTF-8"));
				
				targetLinkList.add(movieLink);
			}
		}
		
		movieInfo.setLinks(targetLinkList);
	}

	private static void print(String msg, Object... args) {
		System.out.println(String.format(msg, args));
	}
}
